<template>
  <div class="editor">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      v-if="showToolbar"
    />
    <Editor
      style="overflow-y: hidden"
      :style="{ height: height + 'px' }"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, watchEffect } from 'vue'


// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 编辑器的模式，默认为default  可选simple （简单模式）
const mode = ref('default')

const valueHtml = ref()

// 编辑器配置
const editorConfig = ref({
  placeholder: '请输入内容...',
  readOnly: props.readOnly,
  MENU_CONF: {
    uploadImage: {
      server: import.meta.env.VITE_APP_BASEURL + '/guide_upload',
      fieldName: 'guideFile',
      allowedFileTypes: ['image/*'],
      headers: {
        Authorization: localStorage.getItem('🎈token')
      }
    }
  }
})

// 工具栏配置项
const toolbarConfig = ref({
  excludeKeys: ['insertVideo', 'uploadVideo', 'group-video']
})

const props = defineProps({
  height: {
    type: Number,
    default: 680
  },
  content: {
    type: String,
    default: ''
  },
  showToolbar: {
    type: Boolean,
    default: true
  },
  readOnly: {
    type: Boolean,
    default: false
  }
})

watchEffect(() => {
  valueHtml.value = props.content
})

/**
 * @description: 获取内容信息
 * @return {*}
 */
const getContent = () => {
  return editorRef.value.getHtml()
}

// 向外导出方法
defineExpose({
  getContent
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = editor => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
</script>

<style scoped lang="scss">
.editor {
  border: 1px solid #ccc;
}
</style>
